<template>
	<view>
		<view class="item" style="padding: 20rpx 30rpx 0; margin-top: 20rpx">
			<u-form :model="model" ref="uform" label-width="auto">
				<view style="height: 50rpx; display: flex; align-items: center">
					<u-icon
						name="order"
						color="#1573FF"
						:label="1 == returnCarType ? '换车信息' : '退车信息'"
						label-color="#333333"></u-icon>
				</view>
				<u-form-item
					:label="1 == returnCarType ? '换车退车时间' : '退车时间'"
					:required="true"
					borderBottom
					@click="timeshow = true">
					<u-input
						:value="1 == returnCarType ? model.timeApply : model.carBackTime"
						inputAlign="right"
						placeholder="请选择时间"
						disabled
						disabledColor="#ffffff"
						@change="change_returnCarTime(returnCarType)"
						border="none"></u-input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item
					label="退车类别"
					v-if="2 == returnCarType"
					:required="true"
					borderBottom
					@click="typeshow = true">
					<u-input
						v-model="model.carTypeStr"
						inputAlign="right"
						placeholder="请选择类别"
						disabled
						disabledColor="#ffffff"
						border="none"></u-input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-form-item label="退车里程数" borderBottom>
					<u-input
						v-model="model.alterationMileage"
						inputAlign="right"
						type="digit"
						disabledColor="#ffffff"
						border="none"
						placeholder="请输入退车里程数"></u-input>
				</u-form-item>

				<u-form-item v-if="1 == returnCarType" label="换车原因" required borderBottom>
					<u-input
						v-model="model.alterationType"
						inputAlign="right"
						disabledColor="#ffffff"
						border="none"
						placeholder="请输入原因"></u-input>
				</u-form-item>

				<u-form-item v-if="2 == returnCarType" label="退车原因" required borderBottom>
					<u-input
						v-model="model.alterationDesc"
						inputAlign="right"
						disabledColor="#ffffff"
						border="none"
						placeholder="请输入原因"></u-input>
				</u-form-item>

				<u-form-item label="车辆退回仓库" borderBottom @click="carWarehouseShow = true">
					<u-input
						v-model="model.depot"
						inputAlign="right"
						disabled
						disabledColor="#ffffff"
						border="none"
						placeholder="请选择退回仓库"></u-input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item
					label="退款时间"
					:required="true"
					borderBottom
					@click="refundShow = true">
					<u-input
						:value="model.refundTime"
						inputAlign="right"
						placeholder="请选择时间"
						disabled
						disabledColor="#ffffff"
						border="none"></u-input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<view v-for="(val, key, i) in model.feeItemConfig" :key="key" v-if="!val.hide">
					<view
						style="
							height: 50rpx;
							display: flex;
							align-items: center;
							padding: 10px 0px;
							border-bottom: 1px solid #e3e6ec;
						">
						<u-icon
							name="order"
							color="#1573FF"
							:label="val.fieldName"
							label-color="#333333"></u-icon>
					</view>
					<u-form-item
						v-for="(item, k, index) in val.feeItemConfig"
						:key="k"
						:label="item.serviceName"
						:required="val.edit && item.valRequired"
						borderBottom>
						<template #labelRight v-if="item.serviceName == '车辆租金欠款金额'">
							<view @click="tip" style="padding-left: 5rpx">
								<u-icon size="18" name="info-circle-fill"></u-icon>
							</view>
						</template>

						<u-input
							v-if="item.serviceProperty == 1 || item.serviceProperty == 2"
							:ref="k"
							v-model="model.feeItemConfig[key]['feeItemConfig'][k].value"
							inputAlign="right"
							type="digit"
							:disabled="!val.edit"
							maxlength="10"
							disabledColor="#ffffff"
							border="none"
							placeholder="请输入"
							@input="inputBlur"></u-input>
						<u-input
							v-else
							v-model="model.feeItemConfig[key]['feeItemConfig'][k].value"
							inputAlign="right"
							type="text"
							:disabled="!val.edit"
							maxlength="200"
							disabledColor="#ffffff"
							border="none"
							placeholder="请输入"
							@input="inputBlur"></u-input>
					</u-form-item>
				</view>

				<!-- <u-form-item label="可退车辆保证金" v-if="2==returnCarType" borderBottom>
					<u-input v-model="model.margin" inputAlign="right" type="digit" disabled
						disabledColor="#ffffff" border="none" placeholder="自动获取">
					</u-input>
				</u-form-item>
				
				<u-form-item label="车辆违章分数" borderBottom>
					<u-input v-model="model.illegalScore" inputAlign="right" type="number"
						disabledColor="#ffffff" border="none" placeholder="请输入车辆违章分数">
					</u-input>
				</u-form-item>
				
				<u-form-item label="车辆违章费用/元" borderBottom>
					<u-input v-model="model.illegalAmount" inputAlign="right" type="digit"
						disabledColor="#ffffff" border="none" placeholder="请输入车辆违章费用">
					</u-input>
				</u-form-item>
				
				<u-form-item label="车辆出险次数" borderBottom>
					<u-input v-model="model.dangerCount" inputAlign="right" type="number"
						disabledColor="#ffffff" border="none" placeholder="请输入车辆出险次数">
					</u-input>
				</u-form-item>
				
				<u-form-item label="车辆出险费用/元" borderBottom>
					<u-input v-model="model.dangerAmount" inputAlign="right" type="digit"
						disabledColor="#ffffff" border="none" placeholder="请输入车辆出险费用">
					</u-input>
				</u-form-item>
				
				<u-form-item label="车辆定损实际定损金额/元" borderBottom>
					<u-input v-model="model.actualAmount" inputAlign="right" type="digit"
						disabledColor="#ffffff" border="none" placeholder="请输入车辆定损实际金额">
					</u-input>
				</u-form-item>
				
				<u-form-item label="车辆可抵扣金额/元" borderBottom>
					<u-input v-model="model.deductionAmount" inputAlign="right" type="digit"
						disabledColor="#ffffff" border="none" placeholder="请输入车辆可抵扣金额">
					</u-input>
				</u-form-item>
				
				<u-form-item label="车辆租金欠款金额/元" borderBottom>
					<u-input v-model="model.rentAmount" inputAlign="right" type="digit" disabled
						disabledColor="#ffffff" border="none" placeholder="自动带出">
					</u-input>
				</u-form-item>
				
				<u-form-item label="车辆违约金额/元" borderBottom>
					<u-input v-model="model.defaultAmount" inputAlign="right" type="digit"
						disabledColor="#ffffff" border="none" placeholder="请输入车辆违约金额">
					</u-input>
				</u-form-item>
				
				<u-form-item label="车辆其它欠款金额/元" borderBottom>
					<u-input v-model="model.otherAmount" inputAlign="right" type="digit"
						disabledColor="#ffffff" border="none" placeholder="请输入车辆其他欠款金额">
					</u-input>
				</u-form-item>
				
				<u-form-item label="费用说明" borderBottom>
					<u-input v-model="model.feeDesc" inputAlign="right"
						disabledColor="#ffffff" border="none" placeholder="请输入费用说明">
					</u-input>
				</u-form-item> -->

				<view style="display: flex; flex-direction: column">
					<u-form-item label="上传凭证">
						<!-- <view class="car-photo" style="padding: 20rpx 0; display: block;font-size: 30rpx;color: #333;">订单附件</view> -->
					</u-form-item>

					<lr-upload
						ref="upload1"
						:objType="1 == returnCarType ? '13' : '14'"
						tag="1"
						@on-change="uploadOnChange"></lr-upload>
				</view>
			</u-form>
		</view>

		<view style="height: 180rpx"></view>

		<view class="tips">
			{{ newAmount < 0 ? '退还金额:' : '补缴金额:' }}￥{{ Math.abs(newAmount) }}
		</view>

		<view class="button-container">
			<button class="btn-item btn-right" @click="commit">确认</button>
		</view>

		<!-- 类型 -->
		<u-picker
			:mode="mode"
			:show="typeshow"
			:default-selector="[0]"
			:columns="rentTypeList"
			keyName="value"
			@confirm="typeConfirm"
			@cancel="typeshow = false"></u-picker>

		<!-- 车辆仓库 -->
		<u-picker
			:mode="mode"
			:show="carWarehouseShow"
			:default-selector="[0]"
			:columns="carWarehouseList"
			keyName="warehouseName"
			@confirm="warehouseConfirm"
			@cancel="carWarehouseShow = false"></u-picker>

		<!-- 时间 -->
		<u-datetime-picker
			:show="timeshow"
			:maxDate="maxDate"
			:minDate="minDate"
			mode="date"
			@confirm="timeConfirm"
			@cancel="timeshow = false"></u-datetime-picker>
		<!-- 退款时间 -->
		<u-datetime-picker
			:show="refundShow"
			mode="date"
			@confirm="refundConfirm"
			@cancel="refundShow = false"></u-datetime-picker>

		<u-modal :show="show" :closeOnClickOverlay="true" @confirm="closeTip" @close="closeTip">
			<view class="slot-content">
				<view>根据公司所设定的退租规则来计算退车租金，退车租金结算方式：</view>
				<div>1、按实际使用天数计算</div>
				<div>2、按原周期账单方式结算</div>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import lrUpload from '@/components/global/lr-upload.vue';
	var moment = require('@/common/moment.js');
	export default {
		components: {
			lrUpload,
		},
		data() {
			return {
				maxDate: moment().add(10, 'years').valueOf(),
				minDate: moment().add(-10, 'years').valueOf(),
				orderCarNo: '',
				returnCarType: '',
				rentType: '',
				orderCarId: '',
				instanceId: '',
				model: {
					uploadAttach: [],
					settleAmount: 0,
					repayType: 0,
					feeItemConfig: {},
				},
				carWarehouseList: [],
				rentTypeList: [],
				carWarehouseShow: false,
				timeshow: false,
				refundShow: false,
				typeshow: false,
				getData: false,
				newAmount: 0,
				show: false,
			};
		},
		watch: {},
		computed: {},
		methods: {
			tip() {
				this.show = true;
			},
			confirm() {
				this.closeTip();
			},
			closeTip() {
				this.show = false;
			},
			// 动态字段失去焦点变化
			inputBlur() {
				let that = this;
				let num = 0;
				for (var key in that.model.feeItemConfig) {
					for (var k in that.model.feeItemConfig[key].feeItemConfig) {
						if (that.model.feeItemConfig[key].feeItemConfig[k].serviceProperty === 1) {
							// num -= Number(that.model.feeItemConfig[key].feeItemConfig[k].value || 0)
							num = Number(num).sub(
								Number(that.model.feeItemConfig[key].feeItemConfig[k].value || 0),
							);
						} else if (
							that.model.feeItemConfig[key].feeItemConfig[k].serviceProperty === 2
						) {
							// num += Number(that.model.feeItemConfig[key].feeItemConfig[k].value || 0)
							num = Number(num).add(
								Number(that.model.feeItemConfig[key].feeItemConfig[k].value || 0),
							);
						} else {
						}
					}
				}
				that.newAmount = num;
			},
			timeConfirm(e) {
				let timeStr = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
				this.timeshow = false;

				if (1 == this.returnCarType) {
					this.model.timeApply = timeStr;
					this.$u.api
						.transferMonthlyRentDebt(
							this.orderCarNo,
							moment(this.model.timeApply).valueOf(),
						)
						.then(res => {
							this.findAndSetOtherAmount(
								this.model,
								'rentAmount',
								this.formatNumber(res.monthlyRentDebt),
							);
						});
				} else {
					this.model.carBackTime = timeStr;
					this.change_returnCarTime();
				}
			},
			change_returnCarTime(returnCarType) {
				console.log(this.model);

				let params = {
					id: this.model.orderCarCode,
					time: moment(this.model.carBackTime).valueOf(),
				};
				// #### 时间车辆租金应退金额
				uni.$u.api.MonthlyRentDebt(params).then(res => {
					if (res.code == 200) {
						// 车辆租金应退金额
						if (
							'rentAmountRefundable' in
							this.model.feeItemConfig?.serviceConfig1?.feeItemConfig
						) {
							this.model.feeItemConfig.serviceConfig1.feeItemConfig.rentAmountRefundable.value =
								res.data.rentAmountRefundable;
						}
						// 车辆租金欠款金额
						if (
							'rentAmountRefundable' in
							this.model.feeItemConfig?.serviceConfig1?.feeItemConfig
						) {
							this.model.feeItemConfig.serviceConfig4.feeItemConfig.rentAmount.value =
								res.data.timeConfirmmonthlyRentDebt;
						}
					}
				});
			},
			findAndSetOtherAmount(obj, name, newValue) {
				let that = this;
				for (const key in obj) {
					if (obj.hasOwnProperty(key)) {
						if (key === name) {
							// 找到 otherAmount 并赋值
							if (typeof obj[key] === 'object') {
								obj[key].value = newValue;
								that.inputBlur();
								that.$forceUpdate();
							} else {
								obj[key] = newValue;
								that.inputBlur();
								that.$forceUpdate();
							}
						} else if (typeof obj[key] === 'object' && obj[key] !== null) {
							// 递归遍历子对象
							this.findAndSetOtherAmount(obj[key], name, newValue);
						}
					}
				}
			},
			formatNumber(money) {
				return new Number(money || 0).toFixed(3).replace(/([0-9]+\.[0-9]{2})[0-9]*/, '$1');
			},
			refundConfirm(e) {
				let timeStr = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
				this.refundShow = false;
				this.model.refundTime = timeStr;
			},

			typeConfirm(e) {
				this.typeshow = false;
				this.model.carType = e.value[0].code;
				this.model.carTypeStr = e.value[0].value;
			},

			warehouseConfirm(e) {
				this.carWarehouseShow = false;
				this.model.depotId = e.value[0].warehouseId;
				this.model.depot = e.value[0].warehouseName;
			},

			//图片上传成功回调
			uploadOnChange(tag, resultList, resultObjList) {
				switch (tag) {
					case '1':
						this.model.uploadAttach = resultObjList;
						break;
				}
			},
			commit() {
				let that = this;

				if (uni.$u.test.isEmpty(that.model.orderId)) {
					this.$u.toast('订单信息获取有误！');
					return;
				}

				if (1 == that.returnCarType) {
					if (uni.$u.test.isEmpty(that.model.timeApply)) {
						this.$u.toast('请选择换车时间！');
						return;
					}
					if (uni.$u.test.isEmpty(that.model.alterationType)) {
						this.$u.toast('请输入换车原因！');
						return;
					}
					if (uni.$u.test.isEmpty(that.model.refundTime)) {
						this.$u.toast('请选择退款时间！');
						return;
					}
				}

				if (2 == that.returnCarType) {
					if (uni.$u.test.isEmpty(that.model.carBackTime)) {
						this.$u.toast('请选择退车时间！');
						return;
					}
					if (uni.$u.test.isEmpty(that.model.carType)) {
						this.$u.toast('请选择退车类型！');
						return;
					}
					if (uni.$u.test.isEmpty(that.model.alterationDesc)) {
						this.$u.toast('请输入退车原因！');
						return;
					}
					if (uni.$u.test.isEmpty(that.model.refundTime)) {
						this.$u.toast('请选择退款时间！');
						return;
					}
				}

				for (const item in that.model.feeItemConfig) {
					let itemVal = that.model.feeItemConfig[item];
					for (const sitem in itemVal.feeItemConfig) {
						let sitemVal = itemVal.feeItemConfig[sitem];
						if (
							itemVal.edit &&
							sitemVal.valRequired &&
							(sitemVal.value == undefined ||
								sitemVal.value == null ||
								sitemVal.value == '')
						) {
							// that.$u.toast('请输入', sitemVal.serviceName)
							uni.showToast({
								title: `请输入${sitemVal.serviceName}`,
								icon: 'error',
							});
							return false;
						}
					}
				}

				// const filterZd = false;
				// for(var key in that.model.feeItemConfig) {
				// 	if(!that.model.feeItemConfig[key].hide&&that.model.feeItemConfig[key].edit){
				// 		for(var k in that.model.feeItemConfig[key].feeItemConfig) {
				// 			if(that.model.feeItemConfig[key].feeItemConfig[k].required){
				// 				if(uni.$u.test.isEmpty(that.model.feeItemConfig[key].feeItemConfig[k].value)){
				// 					this.$u.toast(`请输入${that.model.feeItemConfig[key].feeItemConfig[k].serviceName}`)
				// 					filterZd = true;
				// 					return
				// 				}
				// 			}
				// 		}
				// 	}
				// }
				// if(filterZd){
				// 	return false;
				// }
				uni.showModal({
					content: '确定提交吗?',
					success(res) {
						if (res.confirm) {
							that.$u.api.applyforSave({ ...that.model }).then(res => {
								uni.$emit('refreshOrder', true);
								that.$u.toast('提交成功');
								setTimeout(() => {
									uni.navigateBack();
								}, 1000);
							});
						}
					},
				});
			},
		},
		mounted() {
			let that = this;
			that.$nextTick(function () {
				setTimeout(() => {
					for (var key in that.model.feeItemConfig) {
						for (var k in that.model.feeItemConfig[key].feeItemConfig) {
							if (
								that.model.feeItemConfig[key].feeItemConfig[k].serviceProperty ===
									1 ||
								that.model.feeItemConfig[key].feeItemConfig[k].serviceProperty === 2
							) {
								that.$refs[k][0].setFormatter(e => {
									return e
										.replace(/[^\d.]/g, '')
										.replace(/\.{2,}/g, '.')
										.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
								});
							}
						}
					}
				}, 1500);
			});
			console.log(this.model);
		},
		onLoad(op) {
			this.rentType = 'null' != op.rentType ? op.rentType : '';
			this.orderCarId = 'null' != op.orderCarId ? op.orderCarId : '';
			this.instanceId = op.instanceId ? op.instanceId : '';
			this.orderCarNo = 'null' != op.orderCarNo ? op.orderCarNo : '';
			this.returnCarType = op.returnCarType ? op.returnCarType : '';
			this.carWarehouseList = [this.$store.state.params.warehouseList];
			this.rentTypeList = [this.$store.state.params.getCarCommon.rentType];
			this.model.returnCarType = this.returnCarType;
			if (1 == this.returnCarType) {
				uni.setNavigationBarTitle({
					title: '申请换车',
				});
				this.$u.api
					.transferInfoByOrderCarId({
						orderCarId: this.orderCarId,
					})
					.then(res => {
						let { currTimeStartRent, timeStartRent, timeFinishRent } = res;

						this.maxDate = moment(timeFinishRent).valueOf();
						this.minDate = currTimeStartRent
							? moment(currTimeStartRent).valueOf()
							: moment(timeStartRent).valueOf();
					});
			} else if (2 == this.returnCarType) {
				uni.setNavigationBarTitle({
					title: '申请退车',
				});
			}
			this.$u.api
				.getServiceConfig({
					rentType: this.rentType,
					orderCarId: this.orderCarId,
					suitType: this.returnCarType === '1' ? '2' : '1',
					instanceId: this.instanceId,
				})
				.then(res => {
					this.model.feeItemConfig = res;
					this.inputBlur();
				});
			this.$u.api
				.applyforShow({
					orderCarNo: op.orderCarNo,
				})
				.then(res => {
					this.getData = true;
					this.model.orderId = res.orderId;
					this.model.orderCarId = res.orderCarId;
					this.model.orderCarCode = res.orderCarCode;
					this.model.margin = res.margin;
					this.model.rentAmount = res.rentAmount;
				});
		},
		onReady() {},
	};
</script>

<style lang="scss" scoped>
	.r-content {
		display: flex;
		flex-direction: column;
	}

	.state {
		width: 100%;
		line-height: 118rpx;
		text-align: center;
		font-size: 45rpx;
		color: #ffc000;
		font-weight: bold;
		background-color: #fff;
	}

	.bottom-text {
		display: flex;
		align-items: flex-end;
		height: 50rpx;
		margin-right: 20rpx;
		justify-content: flex-end;
	}

	.tips {
		display: flex;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 100rpx;
		z-index: 998;
		background-color: #1573ff;
		height: 70rpx;
		color: #fff;
		font-size: 26rpx;
		line-height: 70rpx;
		justify-content: center;
	}
</style>
